import {componentMap, constantRoutes} from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ACTIONS: (state, actions) => {
    state.actions = actions
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {...route}
    tmp.component = componentMap[route.component]
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, roles)
    }
    res.push(tmp)
  })

  return res
}

export function filterAsyncActions(routes, roles) {
  let res = []

  routes.forEach(route => {
    const tmp = {...route}
    if (tmp.children) {
      res = res.concat(filterAsyncActions(tmp.children, roles))
    }
    if (tmp.meta && tmp.meta.actions && tmp.meta.actions.length >= 1) {
      res = res.concat(tmp.meta.actions)
    }
  })

  return res
}

const state = {
  routes: [],
  actions: [],
  addRoutes: []
}


const actions = {
  generateRoutes({commit}, roles) {
    return new Promise(resolve => {
      let accessedRoutes = filterAsyncRoutes(roles, roles)
      let actions = filterAsyncActions(roles, roles)
      //accessedRoutes = accessedRoutes || asyncRoutes
      accessedRoutes.push({path: '*', redirect: '/404', hidden: true})
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_ACTIONS', actions)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
